/**
 * 时间格式化 Hook
 * 提供通用的时间格式化功能
 */
export function useTimeFormat() {
  /**
   * 格式化时间字符串为本地化显示
   * @param timeStr 时间字符串或时间戳
   * @param options 格式化选项
   * @returns 格式化后的时间字符串
   */
  const formatTime = (
    timeStr: string | number | Date,
    options?: {
      format?: 'datetime' | 'date' | 'time' | 'relative';
      locale?: string;
    }
  ): string => {
    if (!timeStr) return '无';

    try {
      const date = new Date(timeStr);

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return typeof timeStr === 'string' ? timeStr : '无效时间';
      }

      const { format = 'datetime', locale = 'zh-CN' } = options || {};

      switch (format) {
        case 'datetime':
          return date.toLocaleString(locale);
        case 'date':
          return date.toLocaleDateString(locale);
        case 'time':
          return date.toLocaleTimeString(locale);
        case 'relative':
          return formatRelativeTime(date);
        default:
          return date.toLocaleString(locale);
      }
    } catch (error) {
      console.warn('时间格式化失败:', error);
      return typeof timeStr === 'string' ? timeStr : '格式化失败';
    }
  };

  /**
   * 格式化相对时间（如：5分钟前、2小时前等）
   * @param date 日期对象
   * @returns 相对时间字符串
   */
  const formatRelativeTime = (date: Date): string => {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffSeconds < 60) {
      return '刚刚';
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  };

  /**
   * 格式化时间范围
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @returns 时间范围字符串
   */
  const formatTimeRange = (startTime: string | number | Date, endTime: string | number | Date): string => {
    const start = formatTime(startTime, { format: 'datetime' });
    const end = formatTime(endTime, { format: 'datetime' });
    return `${start} - ${end}`;
  };

  /**
   * 格式化持续时间
   * @param durationMs 持续时间（毫秒）
   * @returns 持续时间字符串
   */
  const formatDuration = (durationMs: number): string => {
    if (durationMs < 0) return '0秒';

    const seconds = Math.floor(durationMs / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) {
      return `${days}天${hours % 24}小时`;
    } else if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟`;
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds % 60}秒`;
    } else {
      return `${seconds}秒`;
    }
  };

  /**
   * 检查时间是否为今天
   * @param date 日期
   * @returns 是否为今天
   */
  const isToday = (date: string | number | Date): boolean => {
    try {
      const targetDate = new Date(date);
      const today = new Date();
      return (
        targetDate.getDate() === today.getDate() && targetDate.getMonth() === today.getMonth() && targetDate.getFullYear() === today.getFullYear()
      );
    } catch {
      return false;
    }
  };

  /**
   * 获取友好的时间显示
   * 今天显示具体时间，昨天显示"昨天 + 时间"，更早显示完整日期
   * @param date 日期
   * @returns 友好的时间字符串
   */
  const formatFriendlyTime = (date: string | number | Date): string => {
    try {
      const targetDate = new Date(date);
      const now = new Date();
      const diffMs = now.getTime() - targetDate.getTime();
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

      if (isToday(targetDate)) {
        return `今天 ${targetDate.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit'
        })}`;
      } else if (diffDays === 1) {
        return `昨天 ${targetDate.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit'
        })}`;
      } else {
        return targetDate.toLocaleString('zh-CN');
      }
    } catch {
      return formatTime(date);
    }
  };

  return {
    formatTime,
    formatRelativeTime,
    formatTimeRange,
    formatDuration,
    isToday,
    formatFriendlyTime
  };
}
